<!-- filename: frontend/src/pages/upload/upload.vue (最终完整版) -->
<template>
  <view class="page-container">
    <view class="upload-form">
      <h1 class="form-title">上传新歌曲</h1>
        <div style="text-align: center;">（不得上传与48系无关人员的翻唱作品）</div>
        <div style="text-align: center;">（人工审核较慢，急的话在“关于”联系我）</div>
        <div style="text-align: center;">（凌晨算前一天，不到白天都是前一天）</div>

      <view class="form-item">
        <text class="label">歌曲名称</text>
        <input class="input" v-model="form.title" placeholder="请输入歌曲名称" />
      </view>

      <view class="form-item">
        <text class="label">歌曲类型</text>
        <radio-group @change="e => form.song_type = e.detail.value" class="radio-group">
          <label><radio value="翻唱" :checked="form.song_type === '翻唱'" />翻唱</label>
          <label><radio value="原创" :checked="form.song_type === '原创'" />原创</label>
        </radio-group>
      </view>

      <view class="form-item">
        <text class="label">翻唱者 (多个用逗号 , 隔开)</text>
        <input class="input" v-model="form.cover_artists" placeholder="例如：陈珂，谭思慧" />
      </view>

      <view class="form-item">
        <text class="label">原唱者 (多个用逗号 , 隔开)</text>
        <input class="input" v-model="form.original_artists" placeholder="例如：周杰伦，林俊杰" />
      </view>

      <view class="form-item">
        <text class="label">翻唱日期</text>
        <picker mode="date" @change="onDateChange">
          <view class="input picker">
            {{ displayDate || '请选择日期' }}
          </view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">语种</text>
        <picker mode="selector" :range="languageList" @change="e => form.language = languageList[e.detail.value]">
          <view class="input picker">{{ form.language || '请选择已有语种' }}</view>
        </picker>
        <input class="input custom-input" v-model="form.language" placeholder="或在此处输入新语种" />
      </view>

      <view class="form-item">
        <text class="label">状态</text>
        <picker mode="selector" :range="statusList" @change="e => form.status = statusList[e.detail.value]">
          <view class="input picker">{{ form.status || '请选择已有状态' }}</view>
        </picker>
        <input class="input custom-input" v-model="form.status" placeholder="或在此处输入新状态" />
      </view>
      
      <view class="form-item">
        <text class="label">音频文件 (mp3, m4a等 / 小于20MB)</text>
        <view v-if="!audioFile" class="file-picker-btn">
          <button type="default" @click="chooseAudio">选择音频</button>
        </view>
        <view v-else class="file-display">
          <text class="file-name">{{ audioFile.name }} ({{ (audioFile.size / 1024 / 1024).toFixed(2) }} MB)</text>
          <button class="cancel-btn" @click="cancelAudio">取消</button>
        </view>
      </view>

      <view class="form-item">
        <text class="label">封面图片 (小于10MB)</text>
        <view v-if="!form.cover_art_url" class="cover-options">
          <button type="default" @click="chooseCover('upload')">上传新封面</button>
          <button type="default" @click="chooseCover('select')">选择已有封面</button>
        </view>
        <view v-else class="file-display">
          <image :src="coverFileUrl" class="cover-preview" mode="aspectFit" />
          <button class="cancel-btn" @click="cancelCover">更改封面</button>
        </view>
      </view>

      <button class="submit-btn" @click="submitUpload" :disabled="isUploading || !isFormValid" :class="{ 'disabled': isUploading || !isFormValid }">
        {{ isUploading ? `上传中...${uploadProgress}%` : '确认上传' }}
      </button>
    </view>
  </view>
  <Player v-if="playerStore.showPlayer" />
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import Player from "@/components/Player.vue";
import { usePlayerStore } from "@/store/player";
import { useAuthStore } from "@/store/auth"; // <-- 在 import 区域添加
import { request } from "@/utils/request";

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
const playerStore = usePlayerStore();
const authStore = useAuthStore(); // <-- 在 setup 内部获取实例
const initialFormState = {
  title: "",
  song_type: "翻唱",
  cover_artists: "",
  original_artists: "",
  cover_date: "",
  language: "",
  status: "",
  cover_art_url: "",
};

const form = reactive({ ...initialFormState });

const audioFile = ref(null);
const coverFile = ref(null);
const coverFileUrl = ref("");
const isUploading = ref(false);
const uploadProgress = ref(0);
const languageList = ref([]);
const statusList = ref([]);
const coverList = ref([]);

onMounted(() => {
  const fetchData = async (url, listRef) => {
    try {
      const data = await request({
        url: url, // request 工具会自动拼接 base URL
        method: 'GET'
      });
      if (Array.isArray(data)) {
        listRef.value = data;
      } else {
        console.error(`Failed to fetch data from ${url}`, data);
      }
    } catch (error) {
      console.error(`Request failed for ${url}`, error);
    }
  };

  fetchData(`/api/languages`, languageList);
  fetchData(`/api/statuses`, statusList);
  fetchData(`/api/covers`, coverList);
});

const displayDate = computed(() => {
  if (!form.cover_date) return "";
  return form.cover_date.replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3");
});

const onDateChange = (e) => {
  form.cover_date = e.detail.value.replace(/-/g, "");
};

const isFormValid = computed(() => {
  const requiredFields = [
    "title",
    "song_type",
    "cover_artists",
    "original_artists",
    "cover_date",
    "language",
    "status",
  ];
  // 增加对 audioFile 和 cover_art_url 的判断
  return (
    requiredFields.every((key) => form[key]) &&
    audioFile.value &&
    form.cover_art_url
  );
});

const chooseAudio = () => {
  uni.chooseFile({
    count: 1,
    type: "audio",
    success: (res) => {
      const file = res.tempFiles[0];
      if (file.size > 20 * 1024 * 1024) {
        uni.showToast({ title: "音频文件不能超过20MB", icon: "none" });
        return;
      }
      audioFile.value = file;
    },
  });
};

const cancelAudio = () => {
  audioFile.value = null;
};

const chooseCover = (type) => {
  if (type === "upload") {
    uni.chooseImage({
      count: 1,
      sizeType: ["compressed"],
      success: (res) => {
        const file = res.tempFiles[0];
        if (file.size > 10 * 1024 * 1024) {
          uni.showToast({ title: "封面图片不能超过10MB", icon: "none" });
          return;
        }
        coverFile.value = file;
        coverFileUrl.value = res.tempFilePaths[0];
        form.cover_art_url = "new_upload";
      },
    });
  } else if (type === "select") {
    if (!coverList.value || coverList.value.length === 0) {
      uni.showToast({ title: "暂无已有封面可选择", icon: "none" });
      return;
    }
    uni.showActionSheet({
      itemList: coverList.value.map((url) => url.split("/").pop()),
      success: (res) => {
        const selectedUrl = coverList.value[res.tapIndex];
        coverFileUrl.value = selectedUrl;
        form.cover_art_url = selectedUrl;
        coverFile.value = null;
      },
    });
  }
};

const cancelCover = () => {
  coverFile.value = null;
  coverFileUrl.value = "";
  form.cover_art_url = "";
};

const resetForm = () => {
  Object.assign(form, initialFormState);
  audioFile.value = null;
  coverFile.value = null;
  coverFileUrl.value = "";
};

const submitUpload = () => {
  if (!isFormValid.value) {
    uni.showToast({ title: "请将所有信息填写完整", icon: "none" });
    return;
  }

  // 【核心新增】在提交前，将用户名添加到 form 对象中
  form.uploader_username = authStore.user.username;

  isUploading.value = true;
  uploadProgress.value = 0;

  const filesToUpload = [];
  filesToUpload.push({ name: "audioFile", uri: audioFile.value.path });
  if (coverFile.value) {
    filesToUpload.push({ name: "coverFile", uri: coverFile.value.path });
  }


  const uploadTask = uni.uploadFile({
    url: `${API_BASE_URL}/api/upload/song`,
    files: filesToUpload,
    filePath: "",
    name: "",
    formData: form,
    header: {
      'Authorization': `Bearer ${authStore.access_token}`
    },
    success: (res) => {
      const data =
        typeof res.data === "string" ? JSON.parse(res.data) : res.data;
      if (res.statusCode === 201) {
        uni.showToast({ title: "上传成功！等待站长审核", icon: "success" });
        resetForm();
        // 【替换为这段代码】
        request({ url: '/api/covers' })
          .then(data => {
            if (Array.isArray(data)) {
              coverList.value = data;
            }
         });
      } else {
        uni.showToast({
          title: `上传失败: ${data.error}`,
          icon: "none",
          duration: 3000,
        });
      }
    },
    fail: (err) => {
      console.error("Upload Fail:", err);
      uni.showToast({ title: "网络请求或上传失败", icon: "error" });
    },
    complete: () => {
      isUploading.value = false;
    },
  });

  uploadTask.onProgressUpdate((res) => {
    uploadProgress.value = res.progress;
  });
};
</script>

<style scoped>
.page-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}
.upload-form {
  width: 100%;
  max-width: 800px;
  padding: 25px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  margin-block-end: 120px;
}
.form-title {
  text-align: center;
  margin-bottom: 25px;
  font-size: 22px;
}
.form-item {
  margin-bottom: 18px;
}
.label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}
.input {
  width: 100%;
  height: 44px;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 0 12px;
  box-sizing: border-box;
  background-color: #f9f9f9;
}
.input:focus {
  border-color: #3cc51f;
  background-color: #fff;
}
.input.picker {
  height: 44px;
  line-height: 44px;
  overflow: hidden;
  text-align: left;
}
.custom-input {
  margin-top: 8px;
}
.radio-group {
  display: flex;
  align-items: center;
  height: 44px;
}
.radio-group label {
  margin-right: 30px;
}
.cover-options {
  display: flex;
  gap: 10px;
}
.submit-btn {
  width: 100%;
  height: 45px;
  line-height: 45px;
  margin-top: 25px;
  background-color: #3cc51f;
  color: white;
  font-size: 16px;
  transition: background-color 0.3s;
}
.submit-btn.disabled {
  background-color: #9ce0a9;
  color: #e0f8e3;
}
button[type=default] {
  background-color: #f8f8f8;
  border: 1px solid #ddd;
}
.file-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 6px;
}
.file-name {
  font-size: 13px;
  color: #555;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 10px;
}
.cover-preview {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  border: 1px solid #eee;
}
.cancel-btn {
  font-size: 12px;
  padding: 4px 8px;
  background-color: #e0e0e0;
  color: #333;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>